package com.turing.common.util;




import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;

import com.itextpdf.kernel.pdf.PdfResources;
import com.itextpdf.kernel.pdf.canvas.parser.PdfCanvasProcessor;

import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.io.RandomAccessFile;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDResources;

import java.io.File;
import java.io.IOException;


public class PdfUtils {

    public static boolean hasImage(String path){

        com.itextpdf.kernel.pdf.PdfReader reader = null;
        PdfDocument document = null;
        try {
            reader = new com.itextpdf.kernel.pdf.PdfReader(path);
            document = new PdfDocument(reader);
            ImageRenderListener listener = new ImageRenderListener();
            PdfCanvasProcessor parser = new PdfCanvasProcessor(listener);

            for (int i = 1; i <= document.getNumberOfPages() && i <= 3; i++) {

                PdfPage page = document.getPage(i);
                parser.processPageContent(page);
                boolean hasImage = listener.get();
                if (hasImage) {
                    System.out.println("image page no:"+i);
                    if( i == 3 || i==document.getNumberOfPages() ){
                        return true;
                    }
                }else {
                    //前三页中，有一页没有图片就走pdf。
                    return false;
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return true;
        }

        return false;
    }

    public static Integer countPDFPage(File pdfFile) {
        try {
            PDFParser parser = new PDFParser(new RandomAccessFile(pdfFile, "r"));
            parser.parse();
            PDDocument pdDocument = parser.getPDDocument();
            int numberOfPages = pdDocument.getNumberOfPages();
            pdDocument.close();
            return numberOfPages;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static Integer countPDFPage2(File pdfFile) {
        PDDocument document=null;
        try {
            document = PDDocument.load(pdfFile);
            // 获取页码
            int pages = document.getNumberOfPages();

            return pages;
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                document.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

    public static void main(String[] args) throws Exception {

//        System.out.println(hasImage("D:\\project\\申购确认单0520.pdf"));
        System.out.println(hasImage("C:\\Users\\zhiqiang\\Desktop\\项目\\产品化\\要素抽取\\新建文件夹\\外汇缴款通知单脱敏样例1.pdf"));

    }

}
